package network.UDP.Chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/22 13:42
 */
public class ReceiveThread implements Runnable{

    private DatagramSocket socket;
    private int port;
    private String name;
    private DatagramPacket datagramPacket;

    public ReceiveThread(int port,String name) {
        this.port = port;
        this.name = name;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while (true){
            try {
                byte[] bytes = new byte[1024];
                datagramPacket = new DatagramPacket(bytes,0,bytes.length);
                socket.receive(datagramPacket);
                String data = new String(bytes, 0, bytes.length);
                if ("再见".equals(data)){
                    break;
                }
                System.out.println(name+":"+ data);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
        System.exit(0);

    }
}
